import os
import schedule
import time
from googleapiclient.discovery import build
import youtube_dl
import json
import logging

logging.basicConfig(filename='downloader.log', level=logging.ERROR, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

# Load configuration from config.json
with open('./config.json', 'r') as f:
    config = json.load(f)

# 配置
ydl_opts = {
    'outtmpl': 'downloads/%(title)s.%(ext)s',
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}

def download_videos():
    print("Entering download_videos() function") # Add print statement
    # 初始化YouTube API客户端
    youtube = build('youtube', 'v3', developerKey=config['api_key'])

    # 获取频道视频列表
    try:
        request = youtube.search().list(
            part='id,snippet',
            channelId=config['channel_id'],
            maxResults=10,
            order='date' # Get latest videos first
        )
        print(f"YouTube API request URL: {request.uri}") # Print request URL
        response = request.execute()
        video_items = response.get('items', [])
        if not video_items:
            print(f"No videos found for channel ID: {config['channel_id']}")
            return
    except Exception as e:
        print(f"Error fetching videos from YouTube API: {e}")
        logging.error(f"YouTube API error: {e}", exc_info=True)
        return

    # Download audio for each video
    ydl = youtube_dl.YoutubeDL(ydl_opts)
    for item in video_items:
        video_id = item['id']['videoId']
        video_title = item['snippet']['title']
        video_url = 'https://youtube.com/watch?v=' + video_id
        output_path = os.path.join('downloads', f"{video_title}.mp3") # Construct expected output path
        if os.path.exists(output_path):
            print(f"Audio file already exists for video: {video_title}. Skipping download.")
            continue # Skip to the next video
        try:
            print(f"Downloading audio for video: {video_title}")
            ydl.download([video_url])
            print(f"Downloaded audio for: {video_title}")
        except Exception as e:
            print(f"Error downloading audio for video {video_title} ({video_url}): {e}")
            logging.error(f"Download error for video {video_title} ({video_url}): {e}", exc_info=True)

# 设置定时任务
schedule.every(1).day.at("08:00").do(download_videos)  # 每天早上8点运行

if __name__ == "__main__":
    print("Starting YouTube audio downloader...")
    try:
        download_videos()
        print("Initial download complete. Starting scheduler...")
    except Exception as e:
        print(f"Unhandled exception: {e}")
        logging.error(f"Unhandled exception: {e}", exc_info=True)
    while True:
        schedule.run_pending()
        time.sleep(1)
